package uk.gov.swmprobation.cplitebase;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;

import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.FlickrException;
import com.googlecode.flickrjandroid.photos.Photo;

public class SaveThumbnail extends AsyncTask<Void,Void,Bitmap>{

	private String photo_id;
	private int project_id;

	// private final Logger logger = LoggerFactory
	// .getLogger(UploadPhotoTask.class);

	public SaveThumbnail(String photo_id,int project_id) {
		Log.e("SaveThumb","Started");
		this.photo_id = photo_id;
		this.project_id = project_id;
		Log.e("SaveThumb","End of Start");
	}
	
	@Override
    protected void onPreExecute() {
		Log.e("SaveThumb","Pre");
    }

	public static Bitmap getFlickrPhoto(String photo_id){
		Log.e("SaveThumb","Start get Photo:"+ photo_id);
		Flickr f = FlickrHelper.getInstance().getFlickr();
		Photo photo;
		Bitmap bm = null;
		try {
			photo = f.getPhotosInterface().getPhoto(photo_id);
			bm = BitmapFactory.decodeStream(photo.getSmallAsInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FlickrException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bm;
	}

	@Override
	protected Bitmap doInBackground(Void... params) {
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(MyApplication.getContext());
		int max_photo_size = (int) (sharedPref.getInt("Max_Picture_Size", 200)*1.8);
		Bitmap photoBitmap = getFlickrPhoto(photo_id);
		if (photoBitmap != null){
			photoBitmap = PhotoTools.resizeBitmap(photoBitmap, max_photo_size);
			File file=new File(MyApplication.getContext().getFilesDir(),project_id+".jpg");
			FileOutputStream fileOutputStream;
			try {
				fileOutputStream = new FileOutputStream(file);
				photoBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fileOutputStream);
				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return photoBitmap;
	}
	
}